<template>
  <!-- 主体区域 -->
  <section id="app">
    <todo-header @my-add="add"></todo-header>
    <todo-main :list="list" @my-del="del"></todo-main>
    <todo-footer
      :list="list"
      @clear-all="list = []"
      v-if="list.length > 0"
    ></todo-footer>
  </section>
</template>

<script>
import TodoFooter from "./components/TodoFooter.vue";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      //测试数据
      // list: [
      //   { id: 1, name: "吃饭", done: true },
      //   { id: 2, name: "睡觉", done: false },
      //   { id: 3, name: "打豆豆", done: true },
      // ],
      list: JSON.parse(localStorage.getItem("list")) || [],
    };
  },
  methods: {
    del(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    add(name) {
      const obj = { id: +new Date(), name, done: false };
      this.list.unshift(obj);
    },
  },
  watch: {
    // 数组是一个复杂数据类型，所以要深度侦听，所以要用完整写法
    list: {
      handler(newVal) {
        localStorage.setItem("list", JSON.stringify(newVal));
      },
      deep: true,
    },
  },
};
</script>

<style>
</style>
